<?php


namespace app\api\services;

use app\api\traits\CommonTrait;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

/**
 * Class JwtService
 * @package app\api\services
 * @desc Token 服务类
 */
class JwtService
{
    use CommonTrait;

    // 获取配置文件
    public static function getConfig()
    {
        $ret['key']    = md5('zq8876!@!');// jwt的签发密钥
        $ret['expire'] = 3600 * 24 * 7;// 失效过期时间
        $ret['iss']    = 'http://www.najingquan.com/';// 签发组织
        $ret['aud']    = "wangqin"; //签发作者
        return self::returnArr(200, '', $ret);
    }

    /**
     * @desc 生成token
     * @param int $userId 用户id
     * @return string
     */
    public static function createJwt($userId = 0)
    {
        $rest   = self::getConfig();
        $config = $rest['data'];
        $key    = $config['key']; //jwt的签发密钥，验证token的时候需要用到
        $time   = time(); //签发时间
        $expire = $time + $config['expire']; //过期时间
        $token  = [
            "user_id" => $userId,
            "iss"     => $config['iss'],//签发组织
            "aud"     => $config['aud'], //签发作者
            "iat"     => $time,
            "nbf"     => $time,
            "exp"     => $expire,
        ];
        $jwt    = JWT::encode($token, $key, 'HS256');
        return $jwt;
    }

    /**
     * @desc 校验jwt token权限API
     * @param string $jwt token值
     * @return array
     */
    public static function verifyJwt($jwt = '')
    {
        $rest   = self::getConfig();
        $config = $rest['data'];
        $key    = $config['key'];
        try {
            $jwtAuth  = json_encode(JWT::decode($jwt, new Key($key, 'HS256')));
            $authInfo = json_decode($jwtAuth, true);

            if (!$authInfo['user_id']) {
                return self::returnArr(40010);
            }
            return self::returnArr(200, '', $authInfo['user_id']);
        } catch (\Firebase\JWT\ExpiredException $e) {
            return self::returnArr(40011);
        } catch (\Exception $e) {
            return self::returnArr(40012);
        }
    }
}